package com.itheima.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    //新增菜品分类
    @PostMapping
    public R<String> CategoryAdd(@RequestBody Category category, HttpSession session) {
        Long employeeId = (Long) session.getAttribute("employee");
        category.setCreateTime(LocalDateTime.now());
        category.setCreateUser(employeeId);
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(employeeId);
        boolean save = categoryService.save(category);
        return save ? R.success("添加菜品成功") : R.error("添加菜品失败");
    }


    //菜品分页查询
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Category::getUpdateTime);
        Page page1 = categoryService.page(pageInfo, queryWrapper);
        return R.success(page1);
    }


    //菜品删除
    @DeleteMapping
    public R<String> delete(Long id) {
        int i = categoryService.deleteById(id);
        return i > 0 ? R.success("删除成功") : R.error("删除失败");
    }


    //修改菜品
    @PutMapping
    public R<Category> Update(@RequestBody Category category, HttpSession session) {
        Long employeeId = (Long) session.getAttribute("employee");
        category.setUpdateUser(employeeId);
        category.setUpdateTime(LocalDateTime.now());
        boolean update = categoryService.updateById(category);
        return update ? R.success(category) : R.error("修改菜品信息失败");
    }


    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}